<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Order as OrderService;
use app\common\service\Material as MaterialService;
use app\common\service\Sku as SkuService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderException as OrderExceptionService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\MaterialStock as MaterialStockService;
use app\common\service\MaterialStockCutting as MaterialStockCuttingService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\OrderMergeCut as OrderMergeCutService;
use think\Db;
/**
 * 物料管理
 * @author King
 *
 */
class Material extends Admin
{

	protected $hisiModel = '';//模型名称[通用添加、修改专用]
	protected $hisiValidate = '';
	protected $hisiAddScene = '';//添加数据验证场景名
	protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();
    }

    /**
     * 物料列表
     *
     * @author KING
     * @date 2020年7月10日
     *
     * @return \think\response\Json|string
     */
    public function index()
    {
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$name    = $this->request->param('name/s');
    		$color    = $this->request->param('color/s');
    		$materialSku    = $this->request->param('material_sku/s');
            $materialSelf_sku=$this->request->param('self_sku/s');
    		$sku    = $this->request->param('sku/s');
    		$clientOrdernum    = $this->request->param('client_ordernum/s');
			$supplier    = $this->request->param('supplier/s');
			$materialType= $this->request->param('material_type');
			if ($supplier != '') {
    			$where[] = ['supplier', 'like', "%{$supplier}%"];
    		}
    		if ($name != '') {
    			$where[] = ['name', 'like', "%{$name}%"];
    		}
            if ($materialSelf_sku != '') {
                $where[] = ['self_sku', 'like', "%{$materialSelf_sku}%"];
            }
            if ($materialType != '') {//1面料里料 2辅料
			    $materialtypeLogic=$materialType==1 ? "<>" : "=";
                $where[] = ['type', $materialtypeLogic, 'accessories'];
            }

    		if ($color != '') {
    			$where[] = ['color', 'like', "%{$color}%"];
    		}
    		if ($materialSku != '') {
    			$where[] = ['material_sku', '=', $materialSku];
    		}
    		if ($clientOrdernum != '') {
    			$where[] = ['id', 'in', db('order_material')->where('client_ordernum', $clientOrdernum)->column('material_id')];
    		}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    if ($ext_id != '') {
                        $temp = db('order o')->field('o.id')->join('order_material om', "o.id=om.order_id", 'left')->where([['o.ext_id', '=', $ext_id]])->column('om.material_id');
                        $where[] = ['id', 'in', $temp];
                    }
                    break;
            }
    		if ($sku != '') {
                $sku_ids=db('sku')->where('sku', $sku)->column('id');
                $sku_ids=count($sku_ids)<1 ? [0] : $sku_ids;
    			$where[] = ['id', 'in', db('sku_material')->where('sku_id', 'in',$sku_ids)->column('material_id')];
    		}

    		$order = 'id desc,use_time desc';
    		$data['data'] = db('material')->where($where)->page($page)->limit($limit)->order($order)->select();
    		$days30 = time()-30*86400;
    		foreach ($data['data'] as $k => $v) {
    			$data['data'][$k]['use_orders'] = db('material_log')->where('material_id', $v['id'])->count();
    			$data['data'][$k]['use_orders_30d'] = db('material_log')->where('material_id', $v['id'])->where('update_time', '>=', $days30)->count();
    		}

    		$data['count'] = db('material')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 物料列表选择
     *
     * @author KING
     * @date 2020年7月10日
     *
     * @return \think\response\Json|string
     */
    public function selectItem()
    {
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$name    = $this->request->param('name/s');
    		$color    = $this->request->param('color/s');
    		$materialSku    = $this->request->param('material_sku/s');

    		if ($name != '') {
    			$where[] = ['name', 'like', "%{$name}%"];
    		}
    		if ($color != '') {
    			$where[] = ['color', 'like', "%{$color}%"];
    		}
    		if ($materialSku != '') {
    			$where[] = ['material_sku', '=', $materialSku];
    		}
    		$order = 'use_time desc';
    		$data['data'] = db('material')->where($where)->page($page)->limit($limit)->order($order)->select();
    		$data['count'] = db('material')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}
    	$this->view->engine->layout('system@layout_full');
    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
    	if ($this->request->isPost()) {

    		$postData = $this->request->post();
    		$materialService = new MaterialService();
			/* if ($materialService->checkNameExist($postData['name'])) {
    			return $this->error('该物料名称已存在');
    		} */

    		$postData['material_sku'] = 'TMP'.time();
    		$postData['create_time'] = $postData['update_time'] = time();
    		$id = db('material')->insertGetId($postData);
    		if (!$id) {
    			return $this->error('保存失败');
    		}
    		db('material')->where('id', $id)->update(['material_sku' => "MSKU".$id]);
    		return $this->success('保存成功', '');
    	}
    	$assign = [
    		'unitKV' => getUnitKV(),
    	];

    	$template = $this->request->param('template', 'form');
    	return $this->assign($assign)->fetch($template);
    }

    /**
     * 编辑
     *
     */
    public function edit()
    {
    	$id = $this->request->param('id/d', 0);
    	if ($this->request->isPost()) {// 数据验证

    		$postData = $this->request->post();
    		$materialService = new MaterialService();

    		$postData['update_time'] = time();
    		db('material')->where('id', $id)->update($postData);

    		// 删除物料名称缓存
    		cache(MATERIAL_NAME . $id, null);

    		$upData = [];
    		if ($postData['need_checkcloth'] != 2) {
    			$upData['need_checkcloth'] = $postData['need_checkcloth'];
    		}
    		if ($postData['need_shrink'] != 2) {
    			$upData['need_shrink'] = $postData['need_shrink'];
    		}
    		if ($upData) {
    			db('order_material')->where('material_id', $id)->where('order_id', 'in', db('order')->where('status', 'in', [0,1])->column('id'))->update($upData);
    			db('order_material_item')->where('material_id', $id)->where('order_id', 'in', db('order')->where('status', 'in', [0,1])->column('id'))->update($upData);
    		}
    		return $this->success('保存成功', '');
    	}
		$type=config('mimo.material_type');
		$formData = db('material')->where('id', $id)->findOrEmpty();
    	$this->assign('formData', $formData);
    	$template = $this->request->param('template', 'form');

    	$assign = [
    		'unitKV' => getUnitKV(),
    	];
    	return $this->assign($assign)->fetch($template);
    }

    /**
     * 物料使用订单记录
     *
     * @author KING
     * @date 2020年7月9日
     *
     * @return \think\response\Json|string
     */
    public function history()
    {
    	$materialId = $this->request->param('id/d', 0);
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$name    = $this->request->param('name/s');
    		$color    = $this->request->param('color/s');
    		$sku    = $this->request->param('sku/s');
    		$clientOrdernum    = $this->request->param('client_ordernum/s');

    		if ($materialId) {
    			$where[] = ['material_id', '=', $materialId];
    		}
    		if ($sku != '') {
    			$where[] = ['sku', '=', $sku];
    		}
    		if ($clientOrdernum != '') {
    			$where[] = ['client_ordernum', '=', $clientOrdernum];
    		}

    		$order = 'id desc';
    		$data['data'] = db('material_log')->where($where)->page($page)->limit($limit)->order($order)->select();
    		$data['count'] = db('material_log')->where($where)->count('id');
    		if($data['count']>0){
    		    $materialDosages=db('sku_material')->where([['sku_id','in',array_column($data['data'],'sku_id')],['material_id','eq',$materialId]])->field('sku_id,material_dosage')->select();
    		    $materialDosagesKeyVal=array_column($materialDosages,'material_dosage','sku_id');
                foreach($data['data'] as $key=>&$historypr){
                	$historypr['material_dosage']=arrayGet($materialDosagesKeyVal, $historypr['sku_id'], 0);
                }
            }
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = ['materialId' => $materialId];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 设置需验布
     *
     * @author KING
     * @date 2020年7月10日
     *
     */
	public function setCheckcloth() {
		$id = $this->request->param('id/a');

		$arr['need_checkcloth'] = 1;
		$arr['update_time'] = time();
		db('material')->where('id', 'in', $id)->update($arr);

		$omData = [
			'need_checkcloth' => 1,
		];
		db('order_material')->where('material_id', 'in', $id)->where('order_id', 'in', db('order')->where('status', 'in', [0,1])->column('id'))->update($omData);
		return $this->success('操作成功', '');
	}

	/**
	 * 设置需缩水
	 *
	 * @author KING
	 * @date 2020年7月10日
	 *
	 */
	public function setShrink() {
		$id = $this->request->param('id/a');

		$arr['need_shrink'] = 1;
		$arr['update_time'] = time();
		db('material')->where('id', 'in', $id)->update($arr);

		$omData = [
			'need_shrink' => 1,
		];
		db('order_material')->where('material_id', 'in', $id)->where('order_id', 'in', db('order')->where('status', 'in', [0,1])->column('id'))->update($omData);
		return $this->success('操作成功', '');
	}

	/**
	 * 物料成本核算
	 *
	 * @author KING
	 * @date 2020年7月10日
	 *
	 * @return \think\response\Json|string
	 */
	public function cost()
	{
		$factoryKV = getFactoryKV(true);
		$systemUserKV = getSystemUserKV(null);
		$orderSizeService = new OrderSizeService();
		$materialService = new MaterialService();
		$materialStockCuttingService = new MaterialStockCuttingService();
		$orderMaterialItemService = new OrderMaterialItemService();
		if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
			$where      = $data = [];
            $stat = $this->request->param('a/s','');
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$costAuditStatus    = $this->request->param('cost_audit_status/s');
			$orderStatus    = $this->request->param('order_status/s');
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$costAuditDateRange    = $this->request->param('cost_audit_date_range/s');
			$sku    = $this->request->param('sku/s');
			$isAutoImport    = $this->request->param('is_auto_import/s');
			$createDateRange    = $this->request->param('create_date_range/s');
			$caichuangOverTime    = $this->request->param('caichuang_over_time/s');
			$factorId      = $this->request->param('factory_id/d', 0);
			$exceptionNum      = $this->request->param('exception_num/d', -1);
			$isShare  = $this->request->param('is_share/d', 2);
			$isOmc  = $this->request->param('is_omc/d', 2);
			$export     = $this->request->param('export/d', 0);
			set_time_limit(0);
			ini_set('memory_limit', '1024M');
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}
			if ($isShare!=2) {
				$subQuerys = db('order_material')->where('is_share',$isShare)->distinct(true)->field('order_id')->buildSql();
				$where[] = ['id', 'exp', Db::raw("in({$subQuerys})")];
    		}
			if ($isOmc!=2) {
				$subQueryo = db('order_merge_cut')->distinct(true)->field('client_ordernum')->select();
				$clientOrdernums=[];
				foreach ($subQueryo as $komc => $vomc) {
					$orderNumStr= arrayGet($vomc, "client_ordernum",'');
					$orderNumArr= explode(',', $orderNumStr);
					$clientOrdernums= array_merge($clientOrdernums,$orderNumArr);
				}
				$where[] = ['client_ordernum', 'in', $clientOrdernums];
    		}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', '=', $ext_id];
                    break;
            }
			$where[] = ['status', 'in', [0,1,2]];
			if ($exceptionNum>-1 && $exceptionNum > 0) {
				$where[] = ['exception_num', '>', 0];
			}
			if ($exceptionNum>-1&&$exceptionNum == 0) {
				$where[] = ['exception_num', '=', 0];
			}
			if ($costAuditStatus > -1) {
				$where[] = ['cost_audit_status', '=', $costAuditStatus];
			}
			if ($factorId) {
    			$where[] = ['factory_id', '=', $factorId];
    		}
			if ($isAutoImport > 0) {
				$where[] = ['is_auto_import', '=', $isAutoImport];
			}
			if ($orderStatus != '') {
				switch ($orderStatus){
					case 1:
						$where[] = ['caigou_status', '=', 1];
						$where[] = ['caichuang_status', '=', 0];
						break;
					case 2:
						$where[] = ['caichuang_status', '=', 1];
						$where[] = ['chejian_status', '=', 0];
						break;
					case 3:
						$where[] = ['chejian_status', '=', 1];
						$where[] = ['tail_status', '=', 0];
						break;
					case 4:
						$where[] = ['tail_status', '=', 1];
						$where[] = ['status', '=', 0];
						break;
					case 5:
						$where[] = ['status', '=', 2];
						break;
				}
			}

			if ($clientOrdernum != '') {
				$where[] = ['client_ordernum', 'in', $clientOrdernum];
			}
			if ($sku != '') {
				$where[] = ['sku', 'like', "%".$sku."%"];
			}
			if ($costAuditDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $costAuditDateRange));
				$where[] = ['cost_audit_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($createDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
				$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($caichuangOverTime != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverTime));
				$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
			}
			$order = "cost_audit_status ASC, FIELD(status,1,0,2), caigou_cost_status DESC, id DESC";
			$data['data'] = db('order')->where($where)->page($page)->limit($limit)->orderRaw($order)->select();

			$skuService = new SkuService();
			$orderMaterialService = new OrderMaterialService();
			$orderMergeCutService = new OrderMergeCutService();
			$materialStockService= new MaterialStockService();
			$orderExceptionService= new OrderExceptionService();
			foreach ($data['data'] as $k => $v) {
				$data['data'][$k]['exception']=0;
				$oeList=$orderExceptionService->getListByOrderId($v['id'], 'id');
				if($oeList) $data['data'][$k]['exception']=1;
				$osList = $orderSizeService->getListByOrderId($v['id']);
				$data['data'][$k]['osList'] = $osList;
				$data['data'][$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
				$data['data'][$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
				$data['data'][$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
				$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$data['data'][$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
				$data['data'][$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');
				$data['data'][$k]['omList'] = $orderMaterialService->getListByOrderId($v['id']);
				$data['data'][$k]['om_status']=0;
				$omcInfo=$orderMergeCutService->getInfoByClientOrdernum($v['client_ordernum'], 'id');
				if($omcInfo) $data['data'][$k]['omc_status']=1;
				if ($export) {
					if(!$data['data'][$k]['omList']) unset($v);
				}
				foreach ($data['data'][$k]['omList'] as $kom => $vom) {
					$materialId = $vom['material_id'];
					$trueWeightn=0;
					$trueWeight=db('checkcloth_shrink')->where("order_id=".$vom['order_id']." and material_id=".$vom['material_id'])->column("true_weight");
					if($trueWeight) $data['data'][$k]['omList'][$kom]['true_weight']=$trueWeightn= array_sum($trueWeight)/count($trueWeight);

    				$data['data'][$k]['omList'][$kom]['omiList'] = $orderMaterialItemService->getListByOrderMaterialId($vom['mid']);
    				$data['data'][$k]['omList'][$kom]['mscInfo'] =$mscInfo= $materialStockCuttingService->getInfoByMaterialId($v['id'], $materialId);
    				foreach ($data['data'][$k]['omList'][$kom]['omiList'] as $vomi){
						if ($vomi['caichuang_remark'] != ''){
							$data['data'][$k]['omList'][$kom]['caichuang_remark'].=$vomi['cloth_num_full'].":".$vomi['caichuang_remark']."<br>";
						}
						if (!empty($mscInfo) && $mscInfo['caichuang_remark']!=''){
							$data['data'][$k]['omList'][$kom]['caichuang_remark'].="库存面料：".$mscInfo['caichuang_remark'];
						}
					}
					unset($mscInfo);

					$wkereom=[
						['material_id','=',$vom['material_id']],
						['order_id','=',$vom['order_id']]
					];
					$data['data'][$k]['omList'][$kom]['shiji_weight']=$shijiWeight=round($vom['weight_shrink']-$vom['weight_page'],2);
					$data['data'][$k]['omList'][$kom]['shicai_count']=$shicaiCount=array_sum(array_column($osList, 'shicai_count'));
					$data['data'][$k]['omList'][$kom]['metre']=0;
					$matre = db('material_stock')->field('metre')->where($wkereom)->find();
					if ($matre) $data['data'][$k]['omList'][$kom]['metre']=$matre['metre'];
					$data['data'][$k]['omList'][$kom]['return_num']=db('material_return')->field('id')->where('order_material_id',$vom['mid'])->count();
					$omInfo=$data['data'][$k]['omList'][$kom];
					$heightTotal = array_sum(array_column($omInfo['omiList'], 'caichuang_t_wheat_height'))+arrayGet($omInfo['mscInfo'], 'caichuang_t_wheat_height', 0);
					$lowTotal = array_sum(array_column($omInfo['omiList'], 'caichuang_t_wheat_low'))+arrayGet($omInfo['mscInfo'], 'caichuang_t_wheat_height', 0);
					$neadendTotal = array_sum(array_column($omInfo['omiList'], 'caichuang_t_neadend'))+arrayGet($omInfo['mscInfo'], 'caichuang_t_neadend', 0);
					$stripTotal = array_sum(array_column($omInfo['omiList'], 'caichuang_t_strip'))+arrayGet($omInfo['mscInfo'], 'caichuang_t_strip', 0);
					$allStripDosage=$omInfo['caichuang_strip_dosage']*$shicaiCount;
					$data['data'][$k]['omList'][$kom]['labu_lenght']=$labuLenght=round(($heightTotal*$omInfo['caichuang_wheat_height_length']) + ($lowTotal*$omInfo['caichuang_wheat_low_length']) + $neadendTotal + $stripTotal + $allStripDosage + ($heightTotal+$lowTotal)*0.06, 2);//拉布米长
					$scLenght=$vom['checkcloth_length']==0?$vom['shrink_length']:$vom['checkcloth_length'];
					$data['data'][$k]['omList'][$kom]['metre_dif']=$metreDif=round($scLenght-$vom['billing_caigou_count'],2);//米数差异
					$data['data'][$k]['omList'][$kom]['metre_dif_count']=round($metreDif*$vom['caigou_unitprice'],2); //米数差异金额
					$data['data'][$k]['omList'][$kom]['metre_dif_pre']=$metrePre=($vom['billing_caigou_count']==0?0:round(($vom['checkcloth_length']/$vom['billing_caigou_count']-1)*100,2))."%"; //米数差异率
					$data['data'][$k]['omList'][$kom]['billing_caigou_kgcount_dif']=$billingCaigouKgcountDif=round($shijiWeight-$vom['billing_caigou_kgcount'],2);//公斤差异
					$data['data'][$k]['omList'][$kom]['billing_caigou_kgcount_dif_count']=round($billingCaigouKgcountDif*$vom['billing_caigou_kgprice'],2); //公斤差异金额
					$data['data'][$k]['omList'][$kom]['caigou_unitprice_dif']=$caigouUnitpriceDif=round($vom['customer_price']-$vom['caigou_unitprice'],2);//采购差异
					$data['data'][$k]['omList'][$kom]['caigou_unitprice_dif_count']=round($caigouUnitpriceDif*($vom['customer_dosage'] * (1+$vom['loss']/100))*$shicaiCount,2); //采购差异金额
					$data['data'][$k]['omList'][$kom]['weight_dif']=$weightDif=round(floatval($vom['mInfo']['weight'])-$trueWeightn,2);//克重差异
					$data['data'][$k]['omList'][$kom]['width_dif']=$widthDif=round(floatval($vom['true_fabric_width'])-floatval($vom['mInfo']['fabric_width']),2);//幅宽差异
					$data['data'][$k]['omList'][$kom]['bsp_dif']=$bspDif=round(($vom['customer_dosage']-$vom['caichuang_shiji_dosage']),2);//唛架差异
					$data['data'][$k]['omList'][$kom]['bsp_dif_count']=round($bspDif*$vom['caigou_unitprice']*$shicaiCount,2); //唛架差异金额
					$csLenght=$vom['shrink_length']==0?$vom['checkcloth_length']:$vom['shrink_length'];
					$data['data'][$k]['omList'][$kom]['labu_lenght_dif']=$labuLenghtDif=round($labuLenght-$csLenght,2);//拉布米数差异
					$data['data'][$k]['omList'][$kom]['labu_lenght_dif_count']=round($labuLenghtDif*floatval($vom['caigou_unitprice']),2); //拉布差异金额
					$data['data'][$k]['omList'][$kom]['preCaiCount']=$perCaiCount=$vom['customer_dosage']==0?0:round($vom['billing_caigou_count']/($vom['customer_dosage'] * (1+$vom['loss']/100)),2);//预裁数
					$data['data'][$k]['omList'][$kom]['caichuang_dif']=$caichuangDif=round($shicaiCount-$vom['yingcai_count'],0);//裁剪差异数
					$data['data'][$k]['omList'][$kom]['caichuang_dif_count']=round($caichuangDif*$vom['custom_simple_cost'],2); //裁剪差异金额
				}
				if($data['data'][$k]['omList']){
					$osList=$orderSizeService->getListByOrderId($v['id'], 'shicai_count');
					$data['data'][$k]['omList'][0]['shicai_count'] = array_sum(array_column($osList, 'shicai_count'));
					$data['data'][$k]['shicai_count']=array_sum(array_column($osList, 'shicai_count'));
				}

				unset($oeList, $osList);
			}

			// 导出
			if ($export) {
				$this->_exportXls('物料成本核算-' .date('YmdHis'), $data['data']);
				exit;
			}
            $data['factoryStat']=[];
            if($stat=="factory"){
                $data['factoryStat']=$materialService->getFactoryOrderStat($where);
            }

			$data['count'] = db('order')->where($where)->count('id');
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [
			'factoryKV' => [0 => '请选择'] + $factoryKV,
			'orderFrom' => [0 => '请选择'] + config('mimo.order_from'),
		];
		return $this->assign($assign)->fetch();
	}

	 /**
     * 物料成本核算修改
     *
     * @date 2020年3月10日
     *
     * @throws \Exception
     */
    public function costConfirm() {
    	$mid  = $this->request->param('mid/d', 0);
    	$fabricPriceAmount   = $this->request->param('fabric_price_amount/f', 0);
    	$dosagePriceAmount   = $this->request->param('dosage_price_amount/f', 0);
		$billingCaigouCount   = $this->request->param('billing_caigou_count/f', 0);
    	$customerPrice   = $this->request->param('customer_price/f', 0);

    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();

    	try {
    		db()->startTrans();

	    	// 记录原始开单采购数
	    	$omInfo = $orderMaterialService->getInfoById($mid);
	    	if (empty($omInfo)){
	    		throw new \Exception('数据异常');
	    	}

	    	$oud = [
	    		'update_time' => time(),
	    		'fabric_price_amount' => $fabricPriceAmount,
				'dosage_price_amount' => $dosagePriceAmount,
				'billing_caigou_count' => $billingCaigouCount,
				'customer_price' => $customerPrice,
	    	];

	    	$orderId = $omInfo['order_id'];

	    	$res = db('order_material')->where('mid', $mid)->update($oud);

	    	$this->addOrderLog($orderId, $omInfo['client_ordernum'], '物料成本核算修改');

	    	db()->commit();
	    	return $this->Json(1);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }
	/**
	 * 导出xls
	 *
	 * @author KING date 2020年08月11日
	 *
	 * @param string $fileName
	 * @param array $data
	 */
	private function _exportXls($fileName, $data) {//
		$head = ['账号','下单日期','裁剪日期','图片','订单数','订单类型','供应商','工厂','订单号','SKU','材料名称','开单采购数量','开单采购补量','客户幅宽/克重/米','实际幅宽/克重/米','实裁布封','开单采购公斤数','开单采购公斤价','实际公斤数','采购条数','验布米长','缩水米长','拉布米长','退料匹数','退料米长','单位','客户损耗','采购物料单价','客户物料单价','实际单件用量','客户单件用量','实际单件物料成本','客户单件物料成本','采购物料单项金额', '客户物料单项金额', '盈亏情况','核价','面料核价金额','用量核价金额','预裁数','实裁数','余料金额','余料情况','补损金额','补损明细','米数差异','米数差异金额','米数差异率','公斤数差异','公斤差异金额','采购单价差异','采购差异金额','克重差异','幅宽差异','唛架差异','唛架差异金额','拉布米数差异','拉布差异金额','裁剪差异','裁剪差异金额'];
        $export_material_type=$this->request->param('export_material_type', 'null');
		$phpExcel = getExcelObj();
		$sheet = $phpExcel->setActiveSheetIndex(0);
		$objDate = new \PHPExcel_Shared_Date();
		$objFormat = new \PHPExcel_Style_NumberFormat();
		// 表头处理
		foreach ($head as $k => $v) {
			$cellKey = getExcelLetter($k);
			$sheet->getColumnDimension($cellKey)->setWidth(20);
			$sheet->setCellValue($cellKey . "1", $v);
			$sheet->getRowDimension(1)->setRowHeight(30);
			$sheet->getStyle($cellKey . "1")->getFont()->setBold(true);
			$sheet->getStyle($cellKey . "1")->getAlignment()->setVertical('center');
			$sheet->getStyle($cellKey . "1")->getFont()->getColor()->setARGB("FF0000FF");
		}
		$skuService = new SkuService();
		$row = 2; // 当前行
		$bgArr = array(
			'type' => 'solid',
			'startcolor' => ['rgb' => 'FF0000']
		);

		foreach ($data as $k => $v) {
			if (count($v['omList']) > 1) {
				$accessoriesCount=0;$typeCount=[];
				foreach ($v['omList'] as $kt => $vt) {
					$typeAll[$k][]=$vt['mInfo']['type'];
					$typeCount=array_count_values($typeAll[$k]);
				}
				if(isset($typeCount['accessories'])){
					$accessoriesCount=$typeCount['accessories'];
				}
//				$fabricCount=0;
//				if(!isset($typeCount['fabric'])){
//					$fabricCount=1;
//				}
				$endRow = $row + count($v['omList']) - 1- $accessoriesCount;
				// '下单日期','订单号','SKU','工厂','订单类型'
				//$sheet->mergeCells('A' . $row . ':A' . $endRow)->getStyle('A'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('B' . $row . ':B' . $endRow)->getStyle('B'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('C' . $row . ':C' . $endRow)->getStyle('C'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('D' . $row . ':D' . $endRow)->getStyle('D'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('E' . $row . ':E' . $endRow)->getStyle('E'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('AJ' . $row . ':AJ' . $endRow)->getStyle('AJ'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('F' . $row . ':F' . $endRow)->getStyle('F'. $row)->getAlignment()->setVertical('center');
				//$sheet->mergeCells('G' . $row . ':G' . $endRow)->getStyle('G'. $row)->getAlignment()->setVertical('center');
				//$sheet->mergeCells('H' . $row . ':H' . $endRow)->getStyle('H'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('I' . $row . ':I' . $endRow)->getStyle('I'. $row)->getAlignment()->setVertical('center');
				$sheet->mergeCells('J' . $row . ':J' . $endRow)->getStyle('J'. $row)->getAlignment()->setVertical('center');
				// '采购物料总金额','采购员', '裁剪日期','床号','裁剪员','订单数',

			}
			$bgcolor = 'FFFFFFFF';

			// '下单日期','订单号','SKU','工厂','订单类型'

			if($v['create_time'] > 0){
					$phpExcel->getActiveSheet()->setCellValue('B' . $row, $objDate::PHPToExcel($v['create_time']));
					$phpExcel->getActiveSheet()->getStyle('B' . $row)->getNumberFormat()->setFormatCode($objFormat::FORMAT_DATE_XLSX22);
			}else{
				$sheet->setCellValueExplicit('B' . $row,$v['create_time'],'s');
			}
			if($v['caichuang_over_time'] > 0){
					$phpExcel->getActiveSheet()->setCellValue('C' . $row, $objDate::PHPToExcel($v['caichuang_over_time']));
					$phpExcel->getActiveSheet()->getStyle('C' . $row)->getNumberFormat()->setFormatCode($objFormat::FORMAT_DATE_XLSX22);
			}else{
				$sheet->setCellValueExplicit('C' . $row,'','s');
			}
			// 图片

//			if(in_array(ADMIN_ROLE,[31,22])){
//				$cellVal = $skuService->getPicBySku($v['sku'], false);
//				if ($cellVal && env('env')=='production' && stripos($cellVal, IMG_URL) !== false) {
//					$sheet->getRowDimension($row)->setRowHeight(100);
//					$cellVal = env('root_path') . 'public/' . str_replace(IMG_URL, "", $cellVal);
//
//					$objDrawing = new \PHPExcel_Worksheet_Drawing();
//					// 设置图片路径 切记：只能是本地图片
//					$objDrawing->setPath($cellVal);
//					// 设置图片高度
//					$objDrawing->setWidth(100);
//					// $objDrawing->setHeight(80);
//					// 设置图片要插入的单元格
//					$objDrawing->setCoordinates('D' . $row);
//					// 设置图片所在单元格的格式
//					$objDrawing->setOffsetX(0);
//					$objDrawing->setRotation(0);
//					$objDrawing->getShadow()->setVisible(false);
//					$objDrawing->setWorksheet($sheet);
//				} else {
//					$sheet->setCellValueExplicit('D' . $row, '', 's');
//				}
//			}

			$sheet->setCellValueExplicit('E' . $row, $v['quantity'], 's');//订单数量
			$sheet->setCellValueExplicit('AJ' . $row, $v['caigou_pricing'], 's');	// 核价
			$sheet->setCellValueExplicit('F' . $row, $v['o_type'], 's');	// 订单类型


			$sheet->setCellValueExplicit('I' . $row, $v['client_ordernum'], 's');//订单号
			$sheet->setCellValueExplicit('J' . $row, $v['sku'], 's');

			foreach ($v['omList'] as $sk => $sv) {
				/*  '材料名称','材料类别','开单采购数量','实际采购数量','缩水后数量','单位','采购物料单价','客户物料单价','客户单件用量','实际单件用量','客户单件物料成本','实际单件物料成本','采购物料单项金额','客户物料单项金额', '盈亏情况', */

				$sheet->setCellValueExplicit('G' . $row, $sv['mInfo']['supplier'], 's');//供应商
				$sheet->setCellValueExplicit('A' . $row, arrayGet(config('mimo.order_from'), $v['is_auto_import']), 's');	// 账号
				$sheet->setCellValueExplicit('H' . $row, $v['factory_name'], 's');

				//$sv['customer_price'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'customer_price', 0);
				$sv['weight'] = arrayGet($sv, 'weight', 0);
				$sv['name'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'name', 0);
				$sv['purchasing_unit'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'purchasing_unit', 0);
				$sv['type'] = arrayGet(arrayGet($sv, 'mInfo', ''), 'type', 0);
                if($export_material_type=='accessories'){ //导出辅料
                    if($sv['type']!="accessories") continue;
                }else{
                    if($sv['type']=="accessories") continue;
                }
				$sheet->setCellValueExplicit('K' . $row, $sv['name'], 's');
				if ($sv['billing_caigou_count'] > $sv['shiji_caigou_count']) {
					$sheet->getStyle('L' . $row)->getFill()->applyFromArray($bgArr);
				}
				$sheet->setCellValueExplicit('L' . $row, $sv['billing_caigou_count'], 'n');
				$sheet->setCellValueExplicit('M' . $row, $sv['billing_caigou_count_feed'], 's');
				$metre=round(($sv['mInfo']['fabric_width']==0 || $sv['mInfo']['weight']==0)?0:10000/$sv['mInfo']['fabric_width']/$sv['mInfo']['weight'],2);
				$sheet->setCellValueExplicit('N' . $row, $sv['mInfo']['fabric_width']."/".$sv['mInfo']['weight']."/".$metre, 's');
				$metre_shiji=round(($sv['true_fabric_width']==0 || $sv['true_weight']==0)?0:10000/$sv['true_fabric_width']/$sv['true_weight'],2);
				$sheet->setCellValueExplicit('O' . $row, $sv['true_fabric_width']."/".$sv['true_weight']."/".$metre_shiji, 's');
				$sheet->setCellValueExplicit('P' . $row, $sv['caichuang_fabric_width'], 'n');	// 实裁布封
				$sheet->setCellValueExplicit('Q' . $row, $sv['billing_caigou_kgcount'], 'n');	// 开单采购公斤数
				$sheet->setCellValueExplicit('R' . $row, $sv['billing_caigou_kgprice'], 'n');	// 开单采购公斤价
				$sheet->setCellValueExplicit('S' . $row, $sv['shiji_weight'], 'n');	// 实际公斤数
				$sheet->setCellValueExplicit('T' . $row, $sv['tiaoshu'], 'n');	// 采购条数
				$sheet->setCellValueExplicit('U' . $row, $sv['checkcloth_length'], 'n');	// 验布米长
				$sheet->setCellValueExplicit('V' . $row, $sv['shrink_length'], 'n');	// 缩水米长
				$sheet->setCellValueExplicit('W' . $row, $sv['labu_lenght'], 'n');
				$sheet->setCellValueExplicit('X' . $row, $sv['return_num'], 'n');
				$sheet->setCellValueExplicit('Y' . $row, $sv['return_length'], 'n');
				$sheet->setCellValueExplicit('Z' . $row, $sv['mInfo']['unit'], 's');

				$sheet->setCellValueExplicit('AA' . $row, $sv['loss'], 'n');
				if ($sv['caigou_unitprice'] > $sv['customer_price']) {
					$sheet->getStyle('AB' . $row)->getFill()->applyFromArray($bgArr);
					$sheet->getStyle('AC' . $row)->getFill()->applyFromArray($bgArr);
				}
				$sheet->setCellValueExplicit('AB' . $row, $sv['caigou_unitprice'], 'n');	// 采购物料单价
				$sheet->setCellValueExplicit('AC' . $row, $sv['customer_price'], 'n');		// 客户物料单价
				$shiji_dosage = ($sv['shicai_count'] ? round($sv['billing_caigou_count']/$sv['shicai_count']) : 0);
				if ($shiji_dosage > $sv['customer_dosage']) {
					$sheet->getStyle('AD' . $row)->getFill()->applyFromArray($bgArr);
					$sheet->getStyle('AE' . $row)->getFill()->applyFromArray($bgArr);
				}
				$sheet->setCellValueExplicit('AD' . $row, round($sv['caichuang_shiji_dosage'],2), 'n');//实际单件用量
				$sheet->setCellValueExplicit('AE' . $row, $sv['customer_dosage'], 'n');//客户单件用量

				$sv['shiji_caigou_subtotal_money']=$sv['shicai_count']==0?0:round($sv['caigou_subtotal_money']/$sv['shicai_count'],2);
				$sheet->setCellValueExplicit('AF' . $row, $sv['shiji_caigou_subtotal_money'], 'n');	// 实际单件物料成本
				$sheet->setCellValueExplicit('AG' . $row, $sv['custom_simple_cost'], 'n');		// 客户单件物料成本
				$sheet->setCellValueExplicit('AH' . $row, $sv['caigou_subtotal_money'], 'n'); //采购物料单项金额
				$sheet->setCellValueExplicit('AI' . $row, $sv['custom_simple_cost']*$sv['shicai_count'], 'n');//客户物料单项金额
				$sv['loss_pre']=round(($sv['customer_dosage'] * $sv['customer_price'] * (1+$sv['loss']/100) * $sv['shicai_count'])-$sv['caigou_subtotal_money']+($sv['fabric_price_amount']+$sv['dosage_price_amount']),2);
				$sheet->setCellValueExplicit('AK' . $row, $sv['loss_pre'], 'n');//盈亏情况
				$sheet->setCellValueExplicit('AL' . $row, $sv['fabric_price_amount'], 'n');//面料核价金额
				$sheet->setCellValueExplicit('AM' . $row, $sv['dosage_price_amount'], 'n');//用量核价金额
				$sheet->setCellValueExplicit('AN' . $row, $sv['yingcai_count'], 'n');//预裁数
				$sheet->setCellValueExplicit('AO' . $row, $sv['shicai_count'], 'n');//实裁数
				$sheet->setCellValueExplicit('AP' . $row, $sv['metre']*$sv['caigou_unitprice'], 'n');//余料金额
				$sheet->setCellValueExplicit('AQ' . $row, $sv['metre'], 'n');//余料情况
				$sheet->setCellValueExplicit('AR' . $row, '', 'n');//补损金额
				$sheet->setCellValueExplicit('AS' . $row, '', 'n');//补损明细

				$sheet->setCellValueExplicit('AT' . $row, $sv['metre_dif'], 'n');
                $sheet->setCellValueExplicit('AU' . $row, $sv['metre_dif_count'], 'n');
                $sheet->setCellValueExplicit('AV' . $row, $sv['metre_dif_pre'], 'n');
                $sheet->setCellValueExplicit('AW' . $row, $sv['billing_caigou_kgcount_dif'], 'n');
                $sheet->setCellValueExplicit('AX' . $row, $sv['billing_caigou_kgcount_dif_count'], 'n');
                $sheet->setCellValueExplicit('AY' . $row, $sv['caigou_unitprice_dif'], 'n');
                $sheet->setCellValueExplicit('AZ' . $row, $sv['caigou_unitprice_dif_count'], 'n');
                $sheet->setCellValueExplicit('BA' . $row, $sv['weight_dif'], 'n');
                $sheet->setCellValueExplicit('BB' . $row, $sv['width_dif'], 'n');
                $sheet->setCellValueExplicit('BC' . $row, $sv['bsp_dif'], 'n');
                $sheet->setCellValueExplicit('BD' . $row, $sv['bsp_dif_count'], 'n');
                $sheet->setCellValueExplicit('BE' . $row, $sv['labu_lenght_dif'], 'n');
                $sheet->setCellValueExplicit('BF' . $row, $sv['labu_lenght_dif_count'], 'n');
                $sheet->setCellValueExplicit('BG' . $row, $sv['caichuang_dif'], 'n');
                $sheet->setCellValueExplicit('BH' . $row, $sv['caichuang_dif_count'], 'n');

//				$shiji_dosage = ($sv['shicai_count'] ? round($sv['billing_caigou_count']/$sv['shicai_count']) : 0);
//				if ($shiji_dosage > $sv['customer_dosage']) {
//					$sheet->getStyle('J' . $row)->getFill()->applyFromArray($bgArr);
//					$sheet->getStyle('K' . $row)->getFill()->applyFromArray($bgArr);
//				}
//				$sheet->setCellValueExplicit('J' . $row, $sv['customer_dosage'], 'n');		// 客户单件用量
//				$sheet->setCellValueExplicit('K' . $row, $sv['caichuang_shiji_dosage'], 'n');			// 实际单件用量
//
//				$sheet->setCellValueExplicit('L' . $row, $sv['custom_simple_cost'], 'n');	// 客户单件物料成本
//				$sheet->setCellValueExplicit('M' . $row, ($sv['shicai_count'] ? round($sv['caigou_subtotal_money']/$sv['shicai_count']) : 0), 'n');	// 实际单件物料成本
//				$sheet->setCellValueExplicit('N' . $row, $sv['caigou_subtotal_money'], 'n'); // 采购物料单项金额
//				$khwldxje = round($sv['customer_dosage'] * $sv['customer_price'] * (1+$sv['loss']/100) * $sv['shicai_count'], 2);
//				$sheet->setCellValueExplicit('O' . $row, $khwldxje, 'n'); // 客户物料单项金额
//
//				$yk = round($sv['customer_dosage'] * $sv['customer_price'] * (1+$sv['loss']/100) * $sv['shicai_count'] - $sv['caigou_subtotal_money'], 2);
//				$sheet->setCellValueExplicit('P' . $row, $yk, 'n');	//盈亏情况
				// '客户克重', '实际克重', '预裁数', '实裁数', '捆条 ', '配布 ', '布头'
//				$sv['caichuang_strip'] = floatval($sv['caichuang_strip']);
//				$sv['caichuang_neadend'] = floatval($sv['caichuang_neadend']);
//				$sv['caichuang_adaption'] = floatval($sv['caichuang_adaption']);
//				$ycs = $sv['customer_dosage']>0 ? round(($sv['shrink_length']-$sv['caichuang_strip']-$sv['caichuang_neadend']-$sv['caichuang_adaption'])/($sv['customer_dosage'] * (1+$sv['loss']/100)), 2) : 0;
				$row++;
			}
			unset($v);
			unset($data[$k]);
		}

		// Rename worksheet
		$sheet->setTitle('worksheet');

		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1');
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
		header ('Cache-Control: cache, must-revalidate');
		header ('Pragma: public');

		$objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
		$objWriter->save('php://output');
		exit();
	}

    /**
     * 导出材料用量使用情况统计
     */
	public function exportUseLogList(){
        $order = 'material_sku desc';
        $startTime=strtotime('2022-02-01 00:00:00');
        $endTime=time();
        $where[] = ['om.create_time', 'between', [$startTime, $endTime+86399]];

        $shicaiCountList = db('order_size order_size')
            ->field("order_id,order_size.client_ordernum,sum(order_size.shicai_count) as order_shicai_count,order_size.create_time")
            ->group('order_size.order_id')->buildSql();

        $datalist = db('order_material om')->join('material m', "om.material_id=m.id", 'left')
            ->join([$shicaiCountList=> 'os'], 'om.order_id = os.order_id','left')
            ->field('m.*,om.material_id,material_dosage,count(material_id) as use_count,sum(om.material_dosage * order_shicai_count) as use_total,sum(order_shicai_count) as shicai_count,om.factory_id,om.order_id')
            ->group("om.material_id,factory_id")
            ->where($where)->having("count(material_id) > 4")->order($order)->select();

        $days15= time()-15*86400;
        $where=[];
        $where[] = ['om.material_id', 'in', array_column($datalist,'material_id')];
        $where[] = ['om.create_time', 'between', [$days15, time()+86399]];
        $datalist15= db('order_material om')->join('material m', "om.material_id=m.id", 'left')
            ->join([$shicaiCountList=> 'os'], 'om.order_id = os.order_id','left')
            ->field('m.*,om.material_id,material_dosage,count(material_id) as use_count,sum(om.material_dosage * order_shicai_count) as use_total,sum(order_shicai_count) as shicai_count,om.factory_id,om.order_id')
            ->group("om.material_id,factory_id")
            ->where($where)->having("count(material_id) > 4")->order($order)->select();
        $day15arr=arrayByKey($datalist15,'material_id');
        foreach ($datalist as $key=>&$val){
            $val['shicai_count15']=isset($day15arr[$val['material_id']]) ? $day15arr[$val['material_id']]['shicai_count'] :0;
            $val['use_count15']=isset($day15arr[$val['material_id']]) ? $day15arr[$val['material_id']]['use_count'] :0;
            $val['use_total15']=isset($day15arr[$val['material_id']]) ? $day15arr[$val['material_id']]['use_total'] :0;
        }

        $factoryKV =[0=>'']+getFactoryKV(true);
        $material_type=[''=>'','fabric'=>'面料','lining'=>'里料','accessories'=>'辅料'];
        $assign=[
            'factoryKV'=>$factoryKV,
            'datalist'=>$datalist,
            'mtype'=>$material_type
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 物料进度搜索标签列表
     */
    public function searchLabelList(){
        $useAction=$this->request->param('use_action/s');
        switch ($useAction) {
            case "edit_search_label": //创建与编辑搜索标签
                return $this->addSearchLabel();
                break;
            case"del_search_label": //删除搜索标签
                return $this->delSearchLabel();
                break;
        }
        if ($this->request->isAjax()) {
            $where      = $data = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $name    = $this->request->param('name/s');
            $color    = $this->request->param('color/s');
            $materialSku    = $this->request->param('material_sku/s');
            $sku    = $this->request->param('sku/s');
            $clientOrdernum    = $this->request->param('client_ordernum/s');
            $supplier    = $this->request->param('supplier/s');
            if ($supplier != '') {
                $where[] = ['supplier', 'like', "%{$supplier}%"];
            }
            if ($name != '') {
                $where[] = ['label_name', 'like', "%{$name}%"];
            }
            if ($color != '') {
                $where[] = ['color', 'like', "%{$color}%"];
            }
            if ($materialSku != '') {
                $where[] = ['material_sku', '=', $materialSku];
            }

            $marerialType=['全部','面料','辅料'];//物料类型
            $materialStatus=[1=>'未采购',2=>'采购中',3=>'换料中',4=>'已到料',5=>'未批色',6=>'批色不通过',7=>'已批色',13=>'未发货',14=>'已发货',8=>'批色已齐套',9=>'批色未齐套',10=>'采购未齐套',11=>'采购已齐套',
                15=>'发货未齐套',16=>'发货已齐套',12=>'可裁剪',17=>'已裁床/已车缝/已后整',18=>'已打标',19=>'待退审',20=>'占用已出库']; //搜索物料状态
            $factoryKV =[0=>'未分厂']+getFactoryKV(true);
            $orderTypeArr=[''=>'全部','normal'=>'返单','new'=>'首单','emergent'=>'紧急单','my_first'=>'（奖励）第一次做（不含尾货）','my_return_first'=>'初返'];
            $rolelist=db("system_role")->column("name","id");
            $systemUserKV = getSystemUserKV(null);
            $order = 'update_time desc';
            $data['data'] = db('search_label')->where($where)->page($page)->limit($limit)->order($order)->select();
            foreach ($data['data'] as $k => &$v) {
                $v['materialtype_str']=$marerialType[$v['search_materal_type']];
                $searchMaterialStatus=$v['search_data_status']!='' ? explode(',',$v['search_data_status']) : [];
                $search_marerialStatus=[];
                foreach ($searchMaterialStatus as $key => $value) {
                    $search_marerialStatus[]= arrayGet($materialStatus, $value, '');
                }
                $marerialStatus_str = implode(",", $search_marerialStatus);
                $v['marerialStatus_str'] =$marerialStatus_str;
                $v['order_type']=$orderTypeArr[$v['order_type']];
                $v['admin_user']=$systemUserKV[$v['admin_id']];
                $v['factory_ids_str']=$v['factory_ids']=='' ? "" : $this->_getIdstrNames($v['factory_ids'],$factoryKV);
                $v['visit_roles_str']=$v['visit_role_ids']=='' ? '' : $this->_getIdstrNames($v['visit_role_ids'],$rolelist);
                $v['visit_admins_str']=$v['visit_admin_ids']=='' ? '' : $this->_getIdstrNames($v['visit_admin_ids'],$systemUserKV);
            }
            $data['marerialType']=$marerialType;
            $data['count'] = db('search_label')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $assign = [];
        return $this->assign($assign)->fetch();
    }

    private function _getIdstrNames($strids,$idkeyArr){
        $search_marerialStatus=[];
        $stridsArr = explode(",", $strids);
        foreach ($stridsArr as $key => $value) {
            $search_marerialStatus[]= arrayGet($idkeyArr, $value, '');
        }
        $marerialStatus_str = implode(",", $search_marerialStatus);
        return $marerialStatus_str;
    }

    /**
     *删除搜索标签
     */
    public function delSearchLabel(){
        $id  = $this->request->param('id/d', 0);
        db('search_label')->where('id', $id)->delete();
        $data['code'] = 1;
        $data['msg'] = 'success';
        return json($data);
    }

    /**
     * 增加自定义搜索标签
     */
    public function addSearchLabel(){
        if ($this->request->isPost()) {
            $search_label_id  = $this->request->param('id/d', 0);
            $postData = $this->request->post();
            unset($postData['storehouse_id']);
            if(!empty($postData['empty_factory_order'])){
                $postData['factory_ids']='0,'.$postData['factory_ids'];
                unset($postData['empty_factory_order']);
            }
            if(empty($search_label_id)){
                $postData['admin_id'] =ADMIN_ID;
                $postData['create_time'] = $postData['update_time'] = time();
                $id = db('search_label')->insertGetId($postData);
                if (!$id) {
                    return $this->error('保存失败');
                }
                return $this->success('保存成功', '');
            }else{  //修改搜索标签操作
                $savedata=[];
                if(isset($postData['show_status'])){
                    $savedata['show_status']=$postData['show_status'];
                }
                if(empty($postData['label_color'])){
                    unset($postData['label_color']);
                }
                $savedata=$postData;
                $savedata['admin_id']=ADMIN_ID;
                $savedata['update_time']=time();
                db('search_label')->where('id', $search_label_id)->update($savedata);
                return $this->success('保存成功', '');
            }
        }
        $id  = $this->request->param('id/d', 0);
        $labelInfo=db("search_label")->find($id);
        $assign = [
            'unitKV' => getUnitKV(),
        ];
        $roles=db("system_role")->field("name,id as value")->select();
        $roleNameKey=array_column($roles,'name','id');
        $assign['role_names']=$roleNameKey;

        //可访问的角色
        $use_roles=$labelInfo['visit_role_ids']!='' ? explode(',',$labelInfo['visit_role_ids']) : [];
        $roleArrs=[];
        foreach ($roles as $key=>$txt) {
            $roleArr = ['name' => $txt['name'], 'value' => $txt['value']];
            if(is_array($use_roles) && in_array($txt['value'],$use_roles)){
                $roleArr['selected']=true;
            }
            $roleArrs[]=$roleArr;
        }
        $assign['visit_role_ids']=$roleArrs;

        $factoryKV =[0=>'没有分工厂(未分厂)'] + getFactoryKV(false);
        //搜索工厂
        $use_factoryids=$labelInfo['factory_ids']!='' ? explode(',',$labelInfo['factory_ids']) : [];
        foreach ($factoryKV as $key=>$txt) {
            $factoryArr = ['name' => $txt, 'value' => $key];
            if(is_array($use_factoryids) && in_array($key,$use_factoryids)){
                $factoryArr['selected']=true;
            }
            $factoryList[]=$factoryArr;
        }
        $assign['factorylist']=$factoryList;

        //-------可访问帐号 获取列表供选择
        $audit_users=$labelInfo['visit_admin_ids']!='' ? explode(',',$labelInfo['visit_admin_ids']) : [];
        $systemUserKV = getSystemUserKV(null);
        foreach ($systemUserKV as $key => $value) {
            $auditUser=$otherUser=['name'=>$value,'value'=>$key];
            if(is_array($audit_users) && in_array($key,$audit_users)){
                $auditUser['selected']=true;
            }
            $assign['visit_admin_ids'][]=$auditUser;
        }

        //------------------下拉联动 1级 2级菜单
        $firstMenus=db("system_menu")->where("pid=142")->column("title",'id');
        $secondMenus=db("system_menu")->where([['pid', 'in', array_keys($firstMenus)],['status','eq',1]])->field("id,pid,title")->select();
        $assign['storehouseKV'] = ['' => '请选择'] + $firstMenus;

        $secondMenuList=[];
        foreach ($secondMenus as $key=>$item){
            $secondMenuList[$item['pid']][$item['id']]=$item['title'];
        }
        $storeshelfMap = [];
        foreach ($firstMenus as $k => $v) {
            if ($k > 0)	$storeshelfMap[$k] = $secondMenuList[$k];
        }
        $assign['storeshelfMap'] = $storeshelfMap;
        $newMaterialStatus=[];
        $materialStatus=[1=>'未采购',2=>'采购中',3=>'换料中',4=>'已到料',5=>'未批色',6=>'批色不通过',7=>'已批色',13=>'未发货',14=>'已发货',8=>'批色已齐套',9=>'批色未齐套',10=>'采购未齐套',11=>'采购已齐套',
            15=>'发货未齐套',16=>'发货已齐套',12=>'可裁剪',17=>'已裁床/已车缝/已后整',18=>'已打标',19=>'待退审',20=>'占用已出库'];
        $use_material_status=$labelInfo['search_data_status']!='' ? explode(',',$labelInfo['search_data_status']) : [];
        foreach ($materialStatus as $key=>$txt){
            $otherUser=['name'=>$txt,'value'=>$key];
            if(is_array($use_material_status) && in_array($key,$use_material_status)){
                $otherUser['selected']=true;
            }
            $newMaterialStatus[]=$otherUser;
        }
        $search_materal_type=isset($labelInfo['search_materal_type']) ? $labelInfo['search_materal_type'] : 1; //搜索物料类型 默认显示面料
        $empty_factory_order= empty('factory_ids') || substr($labelInfo['factory_ids'],0,1)==0 ? 1 : 0;
        $bgcolor=empty($labelInfo['label_color']) ? '#009688' :$labelInfo['label_color'];
        $assign['labelInfo']=$labelInfo;
        $assign['bgcolor']=$bgcolor;
        $assign['empty_factory_order']=$empty_factory_order;
        $assign['search_materal_type']=(int)$search_materal_type;
        $assign['materialStatus'] = $newMaterialStatus;
        //$assign['visit_role_ids']=$newMaterialStatus;
        $template = $this->request->param('template', 'edit_search_label');
        return $this->assign($assign)->fetch($template);
    }

	/**
	 * 物料成本核算审核
	 *
	 * @author King
	 * @date 2020年8月5日
	 *
	 */
	public function audit() {
		$orderId       = $this->request->param('order_id/d', 0);

		$orderInfo = (new OrderService())->getInfoById($orderId);
		if (empty($orderInfo)) {
			return $this->error('订单不存在');
		}

		try {
			db()->startTrans();
			$time = time();
			$upData = [
				'cost_audit_status' => 1,
				'cost_audit_time' => $time,
				'update_time' => $time,
			];
			db('order')->where('id', $orderId)->update($upData);

			db()->commit();

			return $this->Json(1);
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}
	/**
	 * 查看合裁订单气泡
	 *
	 * @author 飞燕
	 * @date 2021年5月14日
	 *
	 */
	public function omcOrdernum(){
		$clientOrdernum   = $this->request->param('client_ordernum/s', '');
		if ($this->request->isAjax()) {
			$orderMergeCutService=new OrderMergeCutService();
			$clientOrdernumArr=$orderMergeCutService->getInfoByClientOrdernum($clientOrdernum, 'client_ordernum');
			$data['data']="";
			$data['code']=0;
			if($clientOrdernumArr) {
				$data['code']=1;
				$data['data']=$clientOrdernumArr['client_ordernum'];
			};
			return json($data);
		}

	}
}